<?php
namespace App\Http\Controllers\Api\Promotion;

use Carbon\Carbon;

use App\Models\ConfigureFunction; //功能配置表

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

use App\Service\Pay\WxPayService;

use App\Models\Promotion\Seckill;

use App\Service\Order\SecKillOrderService;

class SeckillBillSubmitController extends Controller
{
    /**
     * 提交订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function billSubmit(Request $request)
    {
        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $mobile = $request->input('mobile');
        $name = $request->input('name');
        $payPwd = $request->input('payPwd');
        $sendId = $request->input('sendId'); //配送时间ID
        $timeID = $request->input('timeID'); //配送时间段ID
        $datetime = Carbon::now();
        $host = $request->getSchemeAndHttpHost();

        if (empty($session_id)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 100002, 'message' => '请登录']);
        }

        /**
         * ===================================
         * 获取团购购物车数据
         * ===================================
         */
        $sec_cart_data = json_decode(Redis::get('G_SEC_KILL_' . $pcustID), true);
        if (!$sec_cart_data) {
            return response()->json(['code' => 100003, 'message' => '暂无秒杀订单信息']);
        }

        if (!isset($sec_cart_data['sendTypeID']) || !in_array($sec_cart_data['sendTypeID'], [1, 2])) {
            return response()->json(['code' => 100003, 'message' => '请选择配送方式']);
        }

        if (!isset($sec_cart_data['deliverid']) || !ebsig_is_int($sec_cart_data['deliverid'])) {
            return response()->json(['code' => 100005, 'message' => '请选择收货地址']);
        }

        $id = $sec_cart_data['activity_id']; //秒杀ID
        $postID = $sec_cart_data['goods'][0]['postID']; //商品ID
        $time_slot_id = $sec_cart_data['goods'][0]['time_slot_id']; //商品ID
        $sendTypeID = $sec_cart_data['sendTypeID']; //配送方式id

        /**
         * ============================
         * 检查秒杀信息
         * ==============================
         */
        $sec_data = Seckill::getCache($id);
        if ( !$sec_data || $sec_data['useFlg'] == 0) {
            return response()->json(['code' => 100004, 'message' => '秒杀已结束']);
        }

        if ( $sec_data['start_date'] > date('Y-m-d') ){
            return response()->json(['code' => 100005, 'message' => '秒杀活动未开始']);
        }
        if ( $sec_data['end_date'] < date('Y-m-d') ) {
            return response()->json(['code' => 100006, 'message' => '秒杀活动已结束']);
        }

        //获取加入购物车的团购商品数据
        $sec_kill_goods = $sec_data['goods'][$time_slot_id]['list'][$postID];
        if (!$sec_kill_goods) {
            return response()->json(['code' => 100007, 'message' => '秒杀商品不存在']);
        }

        $pickup_start_time = null;
        $pickup_end_time = null;
        $send_time = null;

        //送货上门
        if ($sendTypeID == 1) {
            $sec_cart_data['ziti'] = 0;
            $sec_cart_data['sendTypeName'] = '送货上门';

            //查询配送时间信息
            $send_config = ConfigureFunction::getConfigure(12);
            if (!$send_config || !$send_config['detail']) {
                $pickup_start_time = date('Y-m-d H:i:s');
                $pickup_end_time = date('Y-m-d H:i:s',strtotime('+365 day'));
            }

            $send_time_type = $send_config['send_time_type'];
            $send_time = '';
            if ($send_config['detail']) {
                $date = date('Y-m-d', strtotime('+'.$sendId.' days'));
                foreach($send_config['detail'] as &$time){
                    if ($time['timeID'] == $timeID) {
                        if ($send_time_type == 1) {
                            $send_time = $time['timeName'];
                            break;
                        }

                        if ($send_time_type == 2) {
                            $pickup_start_time = $date . ' ' . $time['send_start_time'];
                            $pickup_end_time = $date . ' ' . $time['send_end_time'];
                            break;
                        }

                    }
                }
            }
        }

        //门店自提
        if ($sendTypeID == 2) {
            if (empty($mobile)) {
                return response()->json(['code' => 1000011, 'message' => '请输入提货人手机']);
            } else if (!isMobile($mobile)) {
                return response()->json(['code' => 1000011, 'message' => '提货人手机号码格式错误']);
            }

            if (empty($name)) {
                return response()->json(['code' => 1000011, 'message' => '请输入提货人姓名']);
            }

            //查询自提时间信息
            $ziti_config = ConfigureFunction::getConfigure(13);
            if (!$ziti_config || !$ziti_config['detail']) {
                $pickup_start_time = date('Y-m-d H:i:s');
                $pickup_end_time = date('Y-m-d H:i:s',strtotime('+365 day'));
            }

            if ($ziti_config['detail']) {
                $date = date('Y-m-d', strtotime('+'.$sendId.' days'));
                foreach($ziti_config['detail'] as &$time){
                    if ($time['timeID'] == $timeID) {
                        $pickup_start_time = $date . ' ' . $time['send_start_time'];
                        $pickup_end_time = $date . ' ' . $time['send_end_time'];
                        break;
                    }
                }
            }

            $sec_cart_data['deliver_mobile'] = $mobile;
            $sec_cart_data['deliver_name'] = $name;
            $sec_cart_data['ziti'] = 1;
            $sec_cart_data['sendTypeName'] = '门店自提';
        }

        //获取openId
        $openId = '';
        $customer_redis = json_decode(app('redis')->get('WX_APPLET_USER_' . $session_id), true);
        if (isset($customer_redis['openId']) && !empty($customer_redis['openId'])) {
            $openId = $customer_redis['openId'];
        }

        $sec_cart_data['openId'] = $openId;
        $sec_cart_data['pcustID'] = $pcustID;
        $sec_cart_data['send_time'] = $send_time;
        $sec_cart_data['pickup_start_time'] = $pickup_start_time;
        $sec_cart_data['pickup_end_time'] = $pickup_end_time;
        $sec_cart_data['invoice'] = 0;
        $sec_cart_data['supplier_id'] = 1;;
        $sec_cart_data['payTypeID'] = 50;
        $sec_cart_data['payTypeName'] = '微信支付';
        $sec_cart_data['pay_type'] = 2;
        $sec_cart_data['payPwd'] = $payPwd;
        $sec_cart_data['billPlatform'] = 1; //订单平台
        $sec_cart_data['billChannel'] = 15;//订单渠道
        $sec_cart_data['bill_tariff_money'] = 0;
        $sec_cart_data['host'] = $host;
        $sec_cart_data['max_sale_amount'] = $sec_kill_goods['max_sale_amount'];

        //订单支付信息
        $sec_cart_data['pay'][] = [
            'payTypeID' => 50,
            'payTypeName' => '微信支付',
            'type' => 2,
            'pay_amount' => $sec_cart_data['bill_payable'] > 0 ? $sec_cart_data['bill_payable'] : 0.00,
            'deduct_amount' => 0.00,
            'pay_time' => null
        ];

        //余额使用
        if (isset($sec_cart_data['use_balance']) && !empty($sec_cart_data['use_balance'])) {
            $sec_cart_data['pay'][] = array(
                'payTypeID' => 2,
                'payTypeName' => '余额',
                'type' => 4,
                'pay_amount' => $sec_cart_data['use_balance']['deduct_amount'],
                'deduct_amount' => $sec_cart_data['use_balance']['deduct_amount'],
                'pay_time' => $sec_cart_data['use_balance']['deduct_amount'] == 0 ? $datetime : null
            );
        }


        //积分使用
        if (isset($sec_cart_data['use_points']) && !empty($sec_cart_data['use_points'])) {
            $sec_cart_data['pay'][] = array(
                'payTypeID' => 3,
                'payTypeName' => '积分',
                'type' => 5,
                'pay_amount' => $sec_cart_data['use_points']['points'],
                'deduct_amount' => $sec_cart_data['use_points']['points'],
                'pay_time' => $sec_cart_data['use_points']['points'] == 0 ? $datetime : null
            );
        }

        //实例化团购订单类
        $sec_order_service = new SecKillOrderService($sec_cart_data);

        //新增订单
        $res = $sec_order_service->submit();
        if ( $res['code'] != 200 ) {
            return response()->json(['code' => $res['code'], 'message' => $res['message']]);
        }

        //订单新增成功移除购物车数据
        Redis::del('G_SEC_KILL_' . $pcustID);

        $bill_no = $res['data']['bill_no'];
        $pay_amount = $res['data']['pay_amount'];
        $mallID = $res['data']['mallID'];
        $pay_status = $res['data']['pay_status'];

        $return_data = array(
            'bill_no' => $bill_no,
            'payTypeID' => 50,
            'pay_status' => $pay_status,
            'pay' => []
        );

        if( $pay_status == 1 ){
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_data]);
        }

        $trade_type = '';
        $wx_config_seeting = ConfigureFunction::getConfigureField(41,'wechat_type');
        if ( $wx_config_seeting == 1) {
            $trade_type = 'JSAPI';
        }
        if ( $wx_config_seeting != 1 ) {
            $trade_type = 'NATIVE';
        }

        //微信异步接收路径
        $notify_url = $host . '/onlinepay/weixin/notify';

        $params = [
            'out_trade_no' => $bill_no,
            'trade_type' => $trade_type,
            'payTypeID' => 50,
            'mallID' => $mallID,
            'body' => '微商城',
            'total_fee' => $pay_amount,
            'pcustID' => $pcustID,
            'type' => 4,
            'openId' => $res['data']['openId'],
            'notify_url' => $notify_url
        ];

        $WxPayService = new WxPayService($params);

        $wx_pay = $WxPayService->request();
        if ($wx_pay['code'] == 200) {
            $return_data['pay'] = $wx_pay['data'];
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_data]);

    }

}